<?php

namespace App\Http\Controllers;

use App\Models\CouponModel;
use App\Models\DeliveryModel;
use App\Models\Detection;
use App\Models\OrderGoodsModel;
use App\Models\OrderModel;
use App\Models\RemarkModel;
use App\Models\sf_order;
use App\Models\SfShopCoupon;
use App\Models\ShopModel;
use App\Models\StoreModel;
use App\Sevrice\ApiJwt;
use App\Sevrice\BaiDu;
use App\Sevrice\handleLog;
use App\Sevrice\OrderId;
use App\Sevrice\Pay;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class OrderController extends Controller
{
    /**
     * @param Request $request
     * @return array
     * @throws \Exception
     * 生成订单
     */
    function orderInfoAdd(Request $request)
    {
        //雪花算法生成订单编号
        $order = new OrderId(1);
        $orderSn = $order->next();
        //接受购买商品的id、每个商品id对应的商品数量以及单价
        $buyShopInfo = $request->post('buy_shop');
        if (empty($buyShopInfo)) {
            return ['code' => 400, 'msg' => '请输入购买商品信息buy_shop'];
        }
        //对购买商品信息做数据处理
        $buy = explode('|', $buyShopInfo);
        $price = [];//存储购买商品总价格
        foreach ($buy as $k => $v) {
            $buy[$k] = explode(',', $v);
            $buy[$k]['goods_id'] = $buy[$k][0];
            $buy[$k]['goods_price'] = $buy[$k][1];
            $buy[$k]['goods_number'] = $buy[$k][2];
            $buy[$k]['order_ID'] = $orderSn;
            $buy[$k]['store_num'] = ShopModel::where('shop_id', $buy[$k]['goods_id'])->value('shop_name');
            array_push($price, ($buy[$k]['goods_price'] * $buy[$k]['goods_number']));
            unset($buy[$k][0], $buy[$k][1], $buy[$k][2]);
        }
        $deliveryId = $request->post('delivery_id');
        if (empty($deliveryId)) {
            return ['code' => 400, 'msg' => '请输入delivery_id收货信心id'];
        }
        $arr = DeliveryModel::where('delivery_id', $deliveryId)->first(['delivery_id', 'consignee_name', 'consignee_phone', 'delivery_province'])->toArray();
        $data['delivery_name'] = $arr['consignee_name'];
        $data['delivery_tel'] = $arr['consignee_phone'];
        $data['delivery_address'] = $arr['delivery_province'];
        $data['user_num'] = ApiJwt::decodeToken($request->post('token'));
        $data['order_sn'] = $orderSn;
        $data['pay_channel'] = '';
        $data['order_total'] = array_sum($price);
        $bagCouponId = $request->post('bag_coupon');
        $data['discount_value'] = 0;
        if ($bagCouponId) {
            $couponId = SfShopCoupon::where('cardBag_id', $bagCouponId)->value('coupon_num');
            $data['discount_value'] = CouponModel::where('coupon_id', $couponId)->value('coupon_value');
            $array['coupon_num'] = $couponId;
            $array['use_time'] = date('Y-m-d H:i:s');
            $array['status'] = 1;
            $array['user_num'] = $data['user_num'];
            $array['created_at'] = date('Y-m-d H:i:s');
            DB::table('sf_coupon_log')->insert($array);//记录优惠券使用日志
        }
        $data['order_amount_total'] = $data['order_total'] - $data['discount_value'];
        $data['order_status'] = 0;
        $data['created_at'] = date('Y-m-d H:i:s');
        DB::beginTransaction();
        try {
            sf_order::insert($data);//订单表数据添加
            //循环添加订单对应商品至订单商品表
            for ($i = 0; $i < count($buy); $i++) {
                $buy[$i]['order_goods_sn']=$order->next();
                OrderGoodsModel::insert($buy[$i]);
            }
            DB::commit();
        } catch (QueryException $exception) {
            DB::rollback();
            return ['code' => 400, 'msg' => '生成失败', 'data' => $exception];
        }
        return ['code' => 200, 'msg' => '生成成功', 'data' => $orderSn];
    }

    /**
     * 订单结算
     */
    function paymentOrder(Request $request)
    {
        $orderSn = $request->get('order_sn');
        $total = sf_order::where('order_sn', $orderSn)->value('order_amount_total');
        $type = $request->get('pay_type');
        return Pay::payOrder($type, $orderSn, $total);
    }
    
    /**
     * @return string
     * 支付之后回调页面
     */
    function payLast()
    {
        return ' 支付回调：' . Session::get('error');
    }

    /**
     * @param Request $request
     * @return mixed
     * 个人订单查询
     */
    function orderInfoList(Request $request)
    {
        $userId=ApiJwt::decodeToken($request->get('token'));
        $status = $request->get('order_status');
        $start = $request->get('start_time');
        $end = $request->get('$end');
        $data = sf_order::with('shopInfo')->where(function ($query) use ($userId, $start, $end, $status) {
            if ($userId) {
                $query->where('user_num', $userId);
            }
            if ($end && $start) {
                $query->whereBetween('created_at', [$start, $end]);
            }
            if ($status) {
                $query->where('order_status', $status);
            }
        })->paginate(15)->toArray();
        foreach ($data['data'] as $k => $v) {
            foreach ($v['shop_info'] as $key => $val) {
                $arr = ShopModel::where('shop_id', $val['goods_id'])->first(['shop_nick', 'shop_img']);
                $data['data'][$k]['shop_info'][$key]['goods_id'] = $arr['shop_nick'];
                $storeName = StoreModel::where('store_id', $val['store_num'])->value('store_name');
                $data['data'][$k]['shop_info'][$key]['store_num'] = $storeName;
                $data['data'][$k]['shop_info'][$key]['shop_img'] = $arr['shop_img'];
            }
        }
        return $data;
    }

    /**
     * @param Request $request
     * @return mixed
     * 查询个人检测报告
     */
    function detectionInfoList(Request $request)
    {
        $userId=ApiJwt::decodeToken($request->get('token'));
        $data = Detection::where('user_num', $userId)->get();
        return $data;
    }

    /**
     * @return string
     * 关于我们
     */
    function aboutUs()
    {
        return <<<REGEXP
       <html> 
<head>
<title>关于我们</title>
</head> 
<body>
<div style='width:600px;margin:0 auto'>
<h1 style="color:green">关于我们: </h1>
<img src="https://ts1.cn.mm.bing.net/th?id=ORMS.6dfa3a4bddee005b16509667093a7eee&pid=Wdp&w=300&h=156&qlt=90&c=1&rs=1&dpr=1.25&p=0"></img>
<p>有问题找我们,欢迎致电0718-110-110</p>
</div>
</body> 
<html> 
REGEXP;
    }

    /**
     * @param Request $request
     * @return array
     * @throws \Exception
     * 订单评论
     */
    function remarkOrder(Request $request)
    {
        $goodsSn=$request->post('order_goods_sn');
        $shopId=OrderGoodsModel::where('order_goods_sn',$goodsSn)->value('goods_id');
        $pid=$request->post('pid');
        if(empty($pid)){
            $arr['pid']=0;
        }
        $mark=$request->get('mark');
        if(!preg_match("/^[1-5]$/",$mark)){
           return ['code'=>400,'msg'=>'评分在1-5分'];
        }
        $userId=ApiJwt::decodeToken($request->post('token'));
        $remarkText=$request->post('remark_text');
        $baiDu=new BaiDu();
        $err=$baiDu->conclusion($remarkText);
        if(!$err){
          return ['code'=>400,'msg'=>'内容不合规'];
        }
        $arr=[
            'pid'=>$pid,
            'mark'=>$mark,
            'shop_id'=>$shopId,
            'user_num'=>$userId,
            'remark_text'=>$remarkText,
            'created_at'=>date('Y-m-d H:i:s')
        ];
        DB::beginTransaction();
        try {
            RemarkModel::insert($arr);
            DB::commit();
        }catch (QueryException $exception){
            DB::rollBack();
            return ['code'=>400,'msg'=>'评论失败','data'=>$exception];
        }
//        $orderId=OrderGoodsModel::where('order_goods_sn',$orderSn)->value('order_ID');
//        sf_order::where('order_sn',$orderId)->update(['order_status'=>4]);
        return ['code'=>200,'msg'=>'评论成功'];
    }

    /**
     * @param Request $request
     * @return array|mixed
     * 查询用户评论内容
     */
    function remarkInfo(Request $request){
        $userId=ApiJwt::decodeToken($request->get('token'));
//        $data=RemarkModel::where('user_num',$userId)->where('remark_status','!=',2)->get()->toArray();
        $data=RemarkModel::where('shop_id',$request->get('shop_id'))->get()->toArray();
        $temp=[];
        foreach ($data as $v){
            $v['son']=[];
            $temp[$v['remark_id']]=$v;
        }
        foreach ($temp as $val){
            $temp[$val['pid']]['son'][]=&$temp[$val['remark_id']];
        }

        return isset($temp[0]['son'])?$temp[0]['son']:[];
    }



}
